package com.tianqi.familymap.utils

import android.content.Context


/**
 * Created by Jay on 2015/9/2 0002.
 */
object SPUtils {
    /**
     * 保存在手机里的SP文件名
     */
    const val FILE_NAME = "family"

    /**
     * 保存数据
     */
    fun put(context: Context, key: String?, obj: Any?) {
        val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        val editor = sp.edit()
        if (obj is Boolean) {
            editor.putBoolean(key, (obj as Boolean?)!!)
        } else if (obj is Float) {
            editor.putFloat(key, (obj as Float?)!!)
        } else if (obj is Int) {
            editor.putInt(key, (obj as Int?)!!)
        } else if (obj is Long) {
            editor.putLong(key, (obj as Long?)!!)
        } else {
            editor.putString(key, obj as String?)
        }
        editor.commit()
    }

    /**
     * 获取指定数据
     */
    operator fun get(context: Context, key: String?, defaultObj: Any?): Any? {
        val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        if (defaultObj is Boolean) {
            return sp.getBoolean(key, (defaultObj as Boolean?)!!)
        } else if (defaultObj is Float) {
            return sp.getFloat(key, (defaultObj as Float?)!!)
        } else if (defaultObj is Int) {
            return sp.getInt(key, (defaultObj as Int?)!!)
        } else if (defaultObj is Long) {
            return sp.getLong(key, (defaultObj as Long?)!!)
        } else if (defaultObj is String) {
            return sp.getString(key, defaultObj as String?)
        }
        return null
    }

    /**
     * 删除指定数据
     */
    fun remove(context: Context, key: String?) {
        val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        val editor = sp.edit()
        editor.remove(key)
        editor.commit()
    }

    /**
     * 返回所有键值对
     */
    fun getAll(context: Context): Map<String, *> {
        val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        return sp.all
    }

    /**
     * 删除所有数据
     */
    fun clear(context: Context) {
        val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        val editor = sp.edit()
        editor.clear()
        editor.commit()
    }

    /**
     * 检查key对应的数据是否存在
     */
    fun contains(context: Context, key: String?): Boolean {
        val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        return sp.contains(key)
    }
}